import isPromise from "is-promise";
import { message } from "antd";
import isNil from "lodash/isNil";

export default function promise({ dispatch }) {
  return next => action => {
    return isPromise(action.payload)
      ? action.payload
          .then(response => {
            return dispatch({ ...action, payload: response.data });
          })
          .catch(error => {
            const response = error.response;
            if (isNil(response)) {
              return Promise.reject({ message: error });
            }
            message.error(response.data.message);
            if (response.status === 500) {
              return Promise.reject({ message: response.data.message });
            } else if (error.response.status === 401) {
              window.location.href = "/login";
              return Promise.reject();
            } else {
              return dispatch({
                ...action,
                payload: response.data,
                error: true
              });
            }
          })
          .then(response => {
            if (response && response.payload && !response.payload.success) {
              message.warn(response.payload.message || "业务错误，请检查");
              return Promise.reject();
            }
            return response.payload;
          })
      : next(action);
  };
}
